package config

import (
	"fmt"
	"rc/logger"
	"rc/repo"
)

type LoggerSetting struct {
	Level   string // debug(default) warn error
	Typ     string // console(default) file
	LogPath string // "/tmp/rc.log"(default)
}

type Config struct {
	RepoPath    string // ~/.rc.json(default)
	Logger      LoggerSetting
	ExecTimeout int // default 30second
	BufferSize  int // default 1024*100
}

var config *Config

func GetConfig() *Config {
	if config == nil {
		config = &Config{
			RepoPath: "~/.rc.json",
			Logger: LoggerSetting{
				Level:   "debug",
				Typ:     "console",
				LogPath: "/tmp/rc.log",
			},
			ExecTimeout: 30,
			BufferSize:  1024 * 100,
		}
	}

	return config
}

func (cfg *Config) DisplayConfig() {
	fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
	fmt.Println("Config for *Logger*")
	fmt.Printf("\tLevel: %s\tType: %s\tLogPath: %s\n", cfg.Logger.Level, cfg.Logger.Typ, cfg.Logger.LogPath)
	fmt.Println("")
	fmt.Println("Config for *Repo*")
	fmt.Printf("\tRepo Path: %s\n", cfg.RepoPath)
	fmt.Println("")
	fmt.Println("Config for *Exec*")
	fmt.Printf("\tExec Timeout: %d (seconds)\n", cfg.ExecTimeout)
	fmt.Println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
}

func (cfg *Config) SetRepoPath(p string) error {
	cfg.RepoPath = p

	return repo.InitRepo(cfg.RepoPath)
}

func (cfg *Config) SetLogger(level, typ, logPath string) error {
	if level != "" {
		cfg.Logger.Level = level
	}

	if typ != "" {
		cfg.Logger.Typ = typ
	}

	if logPath != "" {
		cfg.Logger.LogPath = logPath
	}

	return logger.InitLogger(cfg.Logger.Level, cfg.Logger.Typ, cfg.Logger.LogPath)
}

func (cfg *Config) SetExecTimeout(timeout int) error {
	if timeout <= 0 {
		return fmt.Errorf("exec timeout must > 0")
	}

	cfg.ExecTimeout = timeout
	return nil
}

func (cfg *Config) SetBufferSize(bs int) error {
	if bs <= 0 {
		return fmt.Errorf("buffer size must > 0")
	}

	cfg.BufferSize = bs
	return nil
}
